<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Paginator;
use app\admin\model\Node as NodeModel;

class Node extends Admin
{
    public function index()
    {
        $post = input('post.');
        if (!empty($post['search'])) {
            $list = db('node')->where(array('name'=>array('like', '%'.$post['search'].'%')))->paginate(6); 
        } else {
            $list = db('node')->paginate(6);
        }
         
        // var_dump($list);
        return view('admin@node/index', [
            'list' => $list
        ]);
    }

    /**
     * 渲染添加节点页面
     */
    public function add()
    {
        return view('admin@node/add');
    }

    /**
     * 执行添加节点
     */
    public function doAdd()
    {
        $p = input('post.');
        $p['name'] = htmlentities($p['name']);
        $p['mname'] = htmlentities($p['mname']);
        $p['aname'] = htmlentities($p['aname']);
        // dump($p); exit;
        $node = new NodeModel;
        $node->data($p);
        $result = $node->allowField(true)->save();
        if ($result > 0) {
            return $this->success('添加成功!', url('admin/node/index'));
        } else {
            return $this->error('添加失败!');
        }
    }


    /**
     * 渲染编辑节点页面
     */
    public function edit()
    {
        // echo '1111';
        $id = input('param.');
        // var_dump($id);
        $node = db('node')->field(['id','name'])->find($id);
        // var_dump($role);exit;
        return view('admin@node/edit', [
            'node' => $node
        ]);
    }

    /**
     * 执行编辑节点
    */
    public function doEdit()
    {
        // echo '111'; 
        $data = input('param.');
        $data['name'] = htmlentities($data['name']);
        // var_dump($data); exit;
        $id = $data['id'];
        // var_dump($data);
        $result = Db::table('dj_node')->where('id', $id)->update($data);
        // var_dump($result); die;
        if ($result > 0) {
            return $this->success('更新成功!', url('admin/node/index'));
        } else {
            return $this->error('您未修改任何内容!');
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $result = Db::table('dj_node')->delete($id);
        // var_dump($result); exit;
        if ($result > 0) {
            $info['status'] = true;
            $info['id'] = $id;
            $info['info'] = 'ID为:'.$id.'的节点删除成功!';
        } else {
            $info['status'] = false;
            $info['id'] = $id;
            $info['info'] = 'ID为:'.$id.'的节点删除失败!';
        }

        return json($info);
    }


    public function _empty(Request $request)
    {
        return view('/error');
    }

}
